import os
import sys

def process_ls_file():
    # 获取上两级目录路径
    parent_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    imi_dir = os.path.join(parent_dir, '.imi')
    
    # 查找.ls文件
    ls_files = [f for f in os.listdir(imi_dir) if f.endswith('.ls')]
    if not ls_files:
        print("未找到.ls文件")
        return
    
    # 读取第一个.ls文件
    ls_file = os.path.join(imi_dir, ls_files[0])
    with open(ls_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    # 解析内容
    current_func = None
    code_block = []
    functions = {}
    
    for line in lines:
        line = line.strip()
        if line.startswith('.'):
            if current_func:
                functions[current_func] = '\n'.join(code_block)
                code_block = []
            current_func = line[1:]
        else:
            if current_func:
                code_block.append(line)
    
    # 添加最后一个代码块
    if current_func and code_block:
        functions[current_func] = '\n'.join(code_block)
    
    # 在function子目录中查找并执行对应的.py文件
    function_dir = os.path.join(imi_dir, 'function')
    for func_name, code in functions.items():
        py_file = os.path.join(function_dir, f"{func_name}.py")
        if os.path.exists(py_file):
            try:
                # 动态执行代码
                exec(code, globals())
                print(f"成功执行函数: {func_name}")
            except Exception as e:
                print(f"执行函数{func_name}时出错: {str(e)}")
        else:
            print(f"未找到对应的.py文件: {func_name}")

if __name__ == "__main__":
    process_ls_file()